<?php
/**
 *author:韩帅
 *createtime:2017/6/20 18:21
 *description:
 */
namespace App\Http\Controllers\App;

use App\Models\Shop;
use App\Models\User;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;

class ShopLoginController extends Controller
{
    /**
     * 商户登录
     */
    public function shopLogin(Request $request)
    {
        $return   = [];
        //1.参数的接收
        $login    = $request->input('login', '');
        $code     = $request->input('code', '');
        $password = $request->input('password', '');
        //2.参数的判断
        if (/*empty($code) ||*/ empty($login) || empty($password)) {
            return self::error('参数不完整');
        }
        //3.判断验证码是否正确
//        $code     = Session::get('code');
//        if ($code !== $code) {
//            return self::error('验证码错误');
//        }
        //4.账号密码是否正确
        $info = Shop::where('login',$login)->first();
        if (empty($info)) {
            return self::error('账户不存在');
        }
        if ($info['status']   == Shop::STATUS_STOP) {
            return self::error('您的账户已被冻结,请联系管理员');
        }
        if ($info['password'] !== User::create_pwd($password)) {
            return self::error('密码错误');
        }
        //4.商户信息存入session
        //$request->session()->put('shopInfo',['id'=>$info['id']]);
        $request->session()->put('shopInfo',$info);

        $return['id']        = $info['id'];
        $return['shop_name'] = $info['shopname'];
        $return['avatar']    = $info['avatarid'];

        return self::json($return,'成功',200);
    }

    /**
     * 退出登录
     */
    public function shopOut(Request $request) {

        $request->session()->forget('shopInfo');

        return self::success('退出成功');
    }

    /**
     * 密码修改
     */
    public function shopPasswordUpdate(Request $request)
    {

       $shopInfo = $request->session()->get('shopInfo');
       $shopid   = $shopInfo['id'];
       if (empty($shopid)) {
           return self::error('请先登录');
       }

       //1.参数的接收

       $oldPassword    = trim($request->input('oldPassword',''));
       $newPasswordOne = trim($request->input('newPasswordOne',''));
       $newPasswordTwo = trim($request->input('newPasswordTwo',''));

       //2.参数的判断
       if (empty($oldPassword)) {
           return self::error('原始密码不能为空');
       }

       if ($newPasswordOne !== $newPasswordTwo) {
           return self::error('两次输入密码不一致');
       }

       //3.更新密码
       $obj = Shop::where('status',Shop::STATUS_BEGIN)->find($shopid);

       //4.原始密码是否输入正确
       if (User::create_pwd($oldPassword) !== $obj['password']) {
           return self::error('原始密码错误');
       }

       $obj->password = User::create_pwd($newPasswordOne);
       $res = $obj->save();

       if ($res == true) {
           return self::success('成功');
       }

       return self::error('失败');

     }
}